﻿/***************************
* 1.活动列表
* 2.活动详情
****************************/

/* 活动 */
var activity = "activity/list.html";
var activityDetail = "activity/detail.html";
var activitySignUp = "activity/signup.html";

/* 新闻 */
var contactsCallback_activity = myApp.onPageInit('activity', function (page) {

    // 过滤
    $$(".navbar-inner .right img").hide();

    var index_tab1 = 1;
    var size = 10;

    LoadActivityAll(index_tab1, size);
    //加载数据
    function LoadActivityAll(pageindex, pagesize) {
        myApp.showPreloader();
        // 检索条件
        var v_search = [];
        var v_order = [];

        var conditionParams = JSON.stringify({
            // type: 0,
            Identifier: ISS_Constants.Identifier.activity,
            pageIndex: pageindex,
            pageSize: pagesize,
        });

        $$.ajax({
            // url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.CMS,
            url: ISS_Constants.Url.const_activity_url + "?format=json",                    
            crossDomain: true,
            data: { Identifier: ISS_Constants.Identifier.activity,
                    pageIndex: pageindex,
                    pageSize: pagesize },
            timeout: 10000,
            dataType: "jsonp",
            method: "GET",
            success: function (data, status) {
                data = JSON.parse(data);
                loading = false;
                if (data && data.status == "0" && data.results.length > 0) {
                    for (var i = 0; i < data.results.length; i++) {
                        data.results[i].CreateDate = dateFormat(data.results[i].CreateDate);
                        data.results[i].RegistBeginDate = dateFormat(data.results[i].RegistBeginDate);
                        data.results[i].RegistEndDate = dateFormat(data.results[i].RegistEndDate);
                        data.results[i].BeginDate = dateFormat(data.results[i].BeginDate);
                        data.results[i].EndDate = dateFormat(data.results[i].EndDate);

                        if (data.results[i].F_SmallImage == undefined ||
                            data.results[i].F_SmallImage == null || data.results[i].F_SmallImage == "") {
                            data.results[i].F_SmallImage = NoPicture();
                        };
                    };

                    var searchTemplate = $$('#template-activity-tab1').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        $$("#activity_page .content-block ul").append(html);
                    }

                    // 删除加载提示符
                    //$$('.infinite-scroll-preloader').hide();
                    myApp.hidePreloader();
                    if ($$("#activity_page .content-block ul li").length >= data.total) {
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                }
                else {
                    // 删除加载提示符
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    //$$('.infinite-scroll-preloader').remove();
                    myApp.hidePreloader();
                    if (pageindex == 1) {
                        $$("#activity_page .content-block").html(ISS_Element.DIV.noAnswer);
                        $$("#activity_page .noAnswer").on("click", function () {
                            index_tab1 = 1;
                            LoadActivityAll(index_tab1, size);
                        });
                    }
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert("服务器连接失败！");
                loading = false;
            },
            complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                if (status == 'timeout') {//超时,status还有success,error等值的情况
                    myApp.hidePreloader();
                    // ajaxTimeoutTest.abort();
                    myApp.alert("请求超时");
                    loading = false;
                }
            },
        });
    }

    // 下拉滚动加载
    var loading = false; //加载flag
    $$('.infinite-scroll').on('infinite', function () {
        //$$('.infinite-scroll-preloader').show();
        if (loading) return;
        // 设置flag
        loading = true;
        // 模拟1s的加载过程
        setTimeout(function () {
            index_tab1++;
            LoadActivityAll(index_tab1, size);
        }, 100);
    });

});

//时间格式化
function dateFormat(date) {
    if (date != null && date != "" && date != "undefined") {
        var t_date = date.split(" ");
        return t_date.length > 0 ? t_date[0] : "";
    }
    return "";
}

/* 活动详情  */
var contactsCallback_activityDetail = myApp.onPageInit('activityDetail', function (page) {
    //获取页面参数
    var scode = ISS.utils.getParameter("scode");
    var sid = ISS.utils.getParameter("sid");
    var isBackToHome = ISS.utils.getParameter("isBackToHome");
    if (page != undefined) {
        scode = page.query.scode;
    }
    if(isBackToHome && isBackToHome === "true"){
        $$(".previous_go_back").hide();
    }else{
        $$(".home_back").hide();
    }
    var _content = JSON.stringify({
        type: 1,
        Code: scode
    })

    $$.ajax({
        // url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.CMS,
        url: ISS_Constants.Url.const_activity_detail_url + "?format=json",
        crossDomain: true,
        // data: { "content": _content },
        data: {"ContentCode" : scode},
        dataType: "jsonp",
        method: "GET",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.status == "0" && data.results && data.results.length > 0) {

                data.results[0].CreateDate = dateFormat(data.results[0].CreateDate);
                data.results[0].RegistBeginDate = dateFormat(data.results[0].RegistBeginDate);
                data.results[0].RegistEndDate = dateFormat(data.results[0].RegistEndDate);
                data.results[0].BeginDate = dateFormat(data.results[0].BeginDate);
                data.results[0].EndDate = dateFormat(data.results[0].EndDate);
                data.results[0].RegistType = 0;//0:初始化状态；1：直接参与（不需要报名，无人数限制） 2：直接参与（不需要报名，有人数限制） 3：需要报名，不需要审核，无人数限制 4：需要报名，不需要审核，有人数限制 5：需要报名，需要审核，无人数限制 6：需要报名，需要审核，有人数限制
                data.results[0].RegistRole="";
                if (data.results[0].isNeedRegist == 0) {
                    if (data.results[0].isLimitNum == 0) {
                        data.results[0].RegistType = 1;
                        data.results[0].RegistRole="直接参与（不需要报名，无人数限制）";
                    } else if (data.results[0].isLimitNum == 1) {
                        data.results[0].RegistType == 2;
                        data.results[0].RegistRole="直接参与（不需要报名，有人数限制）";
                    }
                } else if (data.results[0].isNeedRegist == 1) {
                    if (data.results[0].isNeedAudit == 0 && data.results[0].isLimitNum == 0) {
                        data.results[0].RegistType = 3;
                        data.results[0].RegistRole="需要报名，不需要审核，无人数限制";
                    } else if (data.results[0].isNeedAudit == 0 && data.results[0].isLimitNum == 1) {
                        data.results[0].RegistType = 4;
                        data.results[0].RegistRole="需要报名，不需要审核，有人数限制";
                    } else if (data.results[0].isNeedAudit == 1 && data.results[0].isLimitNum == 0) {
                        data.results[0].RegistType = 5;
                        data.results[0].RegistRole="需要报名，需要审核，无人数限制";
                    } else if (data.results[0].isNeedAudit == 1 && data.results[0].isLimitNum == 1) {
                        data.results[0].RegistType = 6;
                        data.results[0].RegistRole="需要报名，需要审核，有人数限制";
                    }
                }

                var searchTemplate = $$('#template-activity-detail').html();
                if (searchTemplate) {
                    var compiledSearchTemplate = Template7.compile(searchTemplate);
                    var html = compiledSearchTemplate(data.results[0]);
                    $$("#activity_page_detail .page-content .content-block").html(html);
                }

                //图片
                if (data.results[0].MiddleImage != null && data.results[0].MiddleImage != "undefined") {
                    var array_img = data.results[0].MiddleImage.split(',')
                    if (array_img.length > 0) {
                        for (var i = 0; i < array_img.length; i++) {
                            if (array_img[i] == "")
                                continue;
                            $$(".swiper-container .swiper-wrapper").append(" <div class='swiper-slide'><img src='" + array_img[i] + "'/></div>");
                        }

                        setTimeout(function () {
                            //图片切换
                            var mySwiper = myApp.swiper('.swiper-container', {
                                pagination: '.swiper-pagination'
                            });
                        }, 1000);

                        //图片指点宽度 95%
                        $$("#activity_page_detail .page-content .content-block .card-content .content img").css("width", "100%");
                    }
                }
            }
        },
        error: function (xhr, status) {
            console.log("ajax error!");
        }
    });


    //我要报名
    $$(document).on("click", "#btn_signUp", function (e) {
        $$.ajax({
            url: ISS_Constants.Url.const_yuqing_activity_verification + "?format=json&ContentID=" + sid,
            crossDomain: true,
            dataType: "jsonp",
            method: "POST",
            success: function (data, status) {
                data = JSON.parse(data);
                if (data && data.status != "0") {
                    myApp.alert(data.message);
                }
                else
                    mainView.router.loadPage("signup.html?sid=" + sid + "&scode=" + scode);

            }
        });
    });

});


/* 活动报名  */
var contactsCallback_activitySignUp = myApp.onPageInit('activitySignUp', function (page) {

    var sid = ISS.utils.getParameter("sid");
    var scode = ISS.utils.getParameter("scode");
    var userId = iss_localStorage.get("yuqing_appUserId");
    var userName = iss_localStorage.get("yuqing_appUserName");
    var userTel = iss_localStorage.get("yuqing_appPhone");
    if (userName != null && userName != "" && userName != "undefined")   
        $$("#txtName").val(userName);

    if (userTel != null && userTel != "" && userTel != "undefined")
        $$("#txtTel").val(userTel);
    //提交 
    $$(document).on("click", ".button-signup-submit", function () {
        var name = $$("#txtName").val();
        var tel = $$("#txtTel").val();
        if (name == "") {
            myApp.alert("请填写姓名");
            return;
        }

        if (tel == "") {
            myApp.alert("请填写手机号");
            return;
        }
 
        $$.ajax({
            url: ISS_Constants.Url.const_yuqing_activity_signup + "?format=json&ContentID=" + sid + "&jsonData={CnName:'" + name + "',Phone:'" + tel + "',Sex:" + $$("#selctGender").val() + ",UserID:'" + userId + "'}",
            crossDomain: true,
            dataType: "jsonp",
            method: "POST",
            success: function (data, status) {
                data = JSON.parse(data);
                if (data && data.status != "0") {
                    myApp.alert(data.message);
                }
                else
                    myApp.alert(data.results, function () {
                        mainView.router.loadPage("detail.html?sid=" + sid + "&scode=" + scode);
                    });
            }
        });
    });

    //返回
    $$(document).on("click", ".button-back,.button-signup-cancel", function () {
        mainView.router.loadPage("detail.html?sid=" + sid + "&scode=" + scode);
    });
});

/* 初始化  */
function initData() {
    var href = window.location.href;
    if (href.indexOf(activity) > -1) {
        contactsCallback_activity.trigger();
    }
    else if (href.indexOf(activityDetail) > -1) {
        contactsCallback_activityDetail.trigger();
    }
    else if (href.indexOf(activitySignUp) > -1) {
        contactsCallback_activitySignUp.trigger();
    }
}

initData();

